<template>
  <div class="container">
    <div class="exam-result">
      <div class="title">{{ exam.name }}</div>
      <div>
        <span class="detail">应考人数: <span class="data">{{ exam.total }}</span>人 </span>
        <span class="detail"> 实际考试人数: <span class="data">{{ exam.finished }}</span>人 </span>
        <span class="detail"> 最高分:  <span class="data">{{ highestScore }}</span> 分 </span>
        <span class="detail"> 最低分:  <span class="data">{{ lowestScore }}</span> 分</span>
      </div>
    </div>
    <div class="echart">
      <button @click="exportScore()" class="button">导出</button>
      <div class="table-title">
        各阶段成绩人数统计
        <div class="remark">
          ----数据有延迟,请及时刷新----
        </div>
      </div>
      <OnEchart/>
    </div>

  </div>
    
  </template>
<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { interceptor } from '@/utils/interceptor';
import { reactive } from 'vue';
import OnEchart from './OnEchart.vue'

const route = useRoute();
const examId = route.params.examId;
const exam = reactive({
  id:'',
  name:'',
  finalScore:'',
  className:'',
  total:'',
  finished:'',
  scoresList:[],
}); // 存储考试信息

const scores = ref([]);
// 定义范围（例如：0-20, 21-40, 41-60, 61-80, 81-100,101-120）
const ranges = [
    { min: 0, max: 20, count: 0},
    { min: 21, max: 40, count: 0},
    { min: 41, max: 60, count: 0},
    { min: 61, max: 80, count: 0},
    { min: 81, max: 100, count: 0},
    { min: 101, max: 120, count: 0}
];

onMounted(() => {
  fetchExamDetails();
});

const exportScore = () => {
    const httpInstance = interceptor();

    // 设置 responseType 为 'blob' 来处理二进制数据
    httpInstance({
        method: 'get',
        url: `/teacher/exam/export/${examId}`,
        responseType: 'blob' // 关键点：设置响应类型为 blob
    }).then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', exam.name+'成绩统计.xlsx'); // 下载文件名
        document.body.appendChild(link);
        link.click();
        link.remove();
    }).catch(error => {
        console.error("导出成绩失败：", error);
    });
};


const fetchExamDetails = () => {
  //将examId存储到localStorage
  localStorage.setItem('examId',examId)
  
  const httpInstance = interceptor()

  httpInstance.get(`/teacher/exam/${examId}`)
    .then((res) => {
      console.log("API Response Data:", res.data.data.scoresList);

      exam.id = res.data.data.id;
      exam.name = res.data.data.name;
      exam.finalScore = res.data.data.finalScore;
      exam.className = res.data.data.className;
      exam.total = res.data.data.total;
      exam.finished = res.data.data.finished;
      exam.scoresList = res.data.data.scoresList;

      //处理数据
      scores.value = exam.scoresList.map(item => item.exam_score)
      scores.value.forEach(item => {
        for(let range of ranges){
          if(item >= range.min &&item<=range.max){
            range.count++;
            break;
          }
        }
      });
      const data = ranges.map(range =>range.count);
       localStorage.setItem('data',JSON.stringify(data));
    })
    .catch(error => {
      console.error("获取成绩详情失败:", error);
      if (error.response) {
        console.error("Response Data:", error.response.data); // 打印详细的错误响应数据
      }
    });
};

// 计算最高分和最低分
const highestScore = computed(() => {
  if (exam.scoresList.length === 0) return 0; // 或者根据实际情况返回其他默认值
  return Math.max(...exam.scoresList.map(scoreItem => scoreItem.exam_score));
});

const lowestScore = computed(() => {
  if (exam.scoresList.length === 0) return 0; // 或者根据实际情况返回其他默认值
  return Math.min(...exam.scoresList.map(scoreItem => scoreItem.exam_score));
});
</script>
  
  <style scoped>
  .exam-result {
    display: grid;
    justify-content: center;
  }

  .title{
    font-size: 80px;
    font-weight: 550;
    align-content: center;
 
  }

  .detail{
    font-size:20px;
  }

  .data{
    color:rgb(243, 13, 13);
  }

  .echart{
    margin-top:35px;
    margin-left:12%;
  }

  .button{
    margin-left:15%;
  }

  .table-title{
    font-size: 30px;
    margin-left:28%;
    margin-bottom: 0%;
  }

  .remark{
    font-size:15px;
    color:rgb(245, 57, 14);
  }
  </style>